import { socketsMap } from '@/lib/socket';
import type { NextRequest } from 'next/server';
import { z } from 'zod';

const bodySchema = z.object({
  toIds: z.array(z.string()),
  event: z.string(),
  data: z.any(),
});

//TODO 安全
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const parsedBody = bodySchema.safeParse(body);
    if (!parsedBody.success) {
      return new Response('internal server error');
    }
    const { toIds, event, data } = parsedBody.data;
    for (const userId of toIds) {
      const sockets = socketsMap.get(userId);
      for (const socket of sockets || []) {
        socket.emit(event, data);
      }
    }
    return new Response();
  } catch (error: any) {
    console.error(error);
    return new Response(error.message ?? 'internal server error');
  }
}

export async function GET(request: NextRequest) {
  try {
    const userId = request.nextUrl.searchParams.get('userId');
    const sockets = userId ? socketsMap.get(userId) : null;
    if (sockets && sockets.length > 0) return Response.json('online');
    return Response.json('offline');
  } catch (error) {
    return Response.json('error');
  }
}
